package com.apexsoft.front.common.support;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.apexsoft.front.common.utils.httprequest.OutPacket;

public class BaseFrontController {
	
	private static final Logger log = LogManager.getRootLogger();
	
	/**
	 * ajax return json
	 * @param response
	 * @param jsonArray
	 */
	protected void printJSON(HttpServletResponse response, JSONObject json){
		PrintWriter out = null;
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try{
			out = response.getWriter();
			out.println(JSONObject.toJSONString(json, SerializerFeature.WriteMapNullValue));
		}catch (Exception e){
			log.error(e.getMessage());
		}
		finally{
			out.close();
		}
	}
	
	/**
	 * ajax return json
	 * @param response
	 * @param jsonArray
	 */
	protected void printJSON(HttpServletResponse response, JSONArray json){
		PrintWriter out = null;
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try{
			out = response.getWriter();
			out.println(JSONArray.toJSONString(json, SerializerFeature.WriteMapNullValue));
		}catch (Exception e){
			log.error(e.getMessage());
		}
		finally{
			out.close();
		}
	}
	
	/**
	 * ajax return string
	 * @param response
	 * @param object
	 */
	protected void printString(HttpServletResponse response, String str){
		PrintWriter out  = null;
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try{
			out = response.getWriter();
			out.println(str);
		}
		catch (Exception e){
			log.error(e.getMessage());
		}
		finally{
			out.close();
		}
	}
	
	/**
	 * ajax return json
	 * @param response
	 * @param jsonArray
	 */
	protected void printJSON(HttpServletResponse response, String str){
		PrintWriter out = null;
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try{
			out = response.getWriter();
			out.println(str);
		}catch (Exception e){
			log.error(e.getMessage());
		}
		finally{
			out.close();
		}
	}
	
	/**
	 * 响应json对象
	 * @param response
	 * @param jsonObject
	 */
	protected final void print(HttpServletResponse response,JSONObject jsonObject){
		PrintWriter out = null;
		try{
			//response.setContentType("application/x-json;charset=UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.print(jsonObject);
			out.flush();
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e);
		}finally{
			if(out!=null){
				out.close();
				out = null;
			}
		}
	}
	
	/**
	 * 响应字符串
	 * @param response
	 * @param str
	 */
	protected final void print(HttpServletResponse response,String str){
		PrintWriter out = null;
		try{
			//response.setContentType("application/x-json;charset=UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			out = response.getWriter();
			out.print(str);
			out.flush();
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e);
		}finally{
			if(out!=null){
				out.close();
				out = null;
			}
		}
	}
	
	/**
	 * 获取post的json对象
	 * @param request
	 * @return
	 */
	protected final JSONObject getPostJson(HttpServletRequest request){
		String p = getPostParam(request);
		if(p!=null){
			return JSON.parseObject(p);
		}
		return JSON.parseObject(getPostStr(request));
	}
	
	/**
	 * 获取post的字符串
	 * @param request
	 * @return
	 */
	protected final String getPostStr(HttpServletRequest request){
		try{
			String postStr = this.readStreamParameter(request.getInputStream());
			postStr = java.net.URLDecoder.decode(postStr,"UTF-8");
			return postStr;
		}catch(Exception e){
			e.printStackTrace();
			log.error(e);
			return "{}";
		}
	}
	
	/**
	 * 获取参数json ，只用于测试
	 * @param request
	 * @return
	 */
	private String getPostParam(HttpServletRequest request){
		String p = request.getParameter("p");
		if(p==null||"".equals(p)){
			return null;
		}
		return p;
	}
	
	/**
	 * 获取post数据流的串
	 * @param in
	 * @return
	 */
	protected final String readStreamParameter(ServletInputStream in){  
        StringBuilder buffer = new StringBuilder();  
        BufferedReader reader=null;  
        try{  
            reader = new BufferedReader(new InputStreamReader(in));  
            String line=null;  
            while((line = reader.readLine())!=null){  
                buffer.append(line);  
            }  
        }catch(Exception e){  
            e.printStackTrace();
            log.error(e);
        }finally{  
            if(null!=reader){  
                try {  
                    reader.close();
                    reader = null;
                }catch (IOException e){}  
            }  
        }  
        return buffer.toString();  
    }  
	
	
	protected final void returnToClient(HttpServletRequest request, HttpServletResponse response, OutPacket out) throws IOException{
		response.setHeader("resultCode", String.valueOf(out.getCode()));
		response.setHeader("resultNote", out.getNote());
//		String p = request.getParameter("p");
//		if(p==null||"".equals(p))
//			this.print(response,URLEncoder.encode(out.toJson().toString(), "UTF-8"));
//		else
			this.print(response,out.toJson());
	}
	
	protected final void returnToClient(HttpServletRequest request, HttpServletResponse response, JSONObject out) throws IOException{
//		String p = request.getParameter("p");
//		if(p==null||"".equals(p))
//			this.print(response,URLEncoder.encode(out.toString(), "UTF-8"));
//		else
			this.print(response,out);
	}
	
	protected String getIpAddress(HttpServletRequest request){
		String sip = request.getHeader("X-Real-IP");   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getHeader("x-forwarded-for");   
		}   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getHeader("Proxy-Client-IP");   
		}   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getHeader("WL-Proxy-Client-IP");   
		}   
		if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
		    sip = request.getRemoteAddr();   
		} 
		return sip;
	}

}
